﻿<Serializable()> _
Public Class UpdateQuery
    Inherits Query

    Protected mTableName As String
    Protected mFields As List(Of KeyValuePair(Of String, String))
    Protected mCriteria As List(Of ICriteriaComponent)


    Public Property TableName() As String
        Get
            Return mTableName
        End Get
        Set(ByVal value As String)
            mTableName = value
        End Set
    End Property

    Public ReadOnly Property Criteria() As List(Of ICriteriaComponent)
        Get
            Return mCriteria
        End Get
    End Property

    Public ReadOnly Property Fields() As List(Of KeyValuePair(Of String, String))
        Get
            Return mFields
        End Get
    End Property

    Public Sub New()
        mFields = New List(Of KeyValuePair(Of String, String))
        mCriteria = New List(Of ICriteriaComponent)
    End Sub

    Public Sub AddCriteria(ByVal Criteria As ICriteriaComponent)
        If Criteria Is Nothing Then
            Throw New InvalidOperationException("You may not add Nothing as a criteria.")
        End If
        mCriteria.Add(Criteria)
    End Sub

    Public Sub AddField(ByVal FieldName As String, ByVal Value As String)
        Dim Field As New KeyValuePair(Of String, String)(FieldName, Value)
    End Sub

    Public Overrides Function GetSQLText(Options As QueryOptions) As String
        Dim ret As String = "UPDATE " & mTableName
        ret &= " SET "

        Dim Parts As New List(Of String)
        For Each Field As KeyValuePair(Of String, String) In mFields
            If Field.Value.StartsWith("@") Then
                Parts.Add(Field.Key & "= " & Field.Value)
            Else
                Parts.Add(Field.Key & "= '" & Field.Value & "'")
            End If
        Next
        ret &= Join(Parts.ToArray, ", ")


        'Only use criteria that should render
        Dim RenderList As New List(Of ICriteriaComponent)
        For Each Criteria As ICriteriaComponent In mCriteria
            If Criteria.HasContent Then
                RenderList.Add(Criteria)
            End If
        Next

        If RenderList.Count > 0 Then
            ret &= " WHERE "
            For i As Integer = 0 To RenderList.Count - 1 Step 1
                Dim Criteria As ICriteriaComponent = RenderList(i)
                If i < RenderList.Count - 1 Then
                    ret &= Criteria.GetText & " AND "
                Else
                    ret &= Criteria.GetText
                End If
            Next
        End If

        Return ret
    End Function
End Class
